// const viewGenerator = require('./plop-templates/view/prompt')
'use strict'
var fs = require('fs')
module.exports = function(plop) {
  const params = process.argv.slice(2)
  const routerFileName = params.length ? params[0] : ''
  if (!routerFileName) {
    throw new Error('缺少路由文件参数')
  }
  const filePath = 'src/router/modules/' + routerFileName + '.js'

  plop.setGenerator('view', {
    description: 'generate a view',
    prompts: [
      {
        type: 'input',
        name: 'name',
        message: 'view name please'
        // validate: notEmpty('name')
      }
    ],
    actions: data => {
      var routerArr = fs.readFileSync(filePath, 'utf8')
      const fileData = routerArr.split('export default')[1].replace(/Layout/g, '1')
      const routers = handelRouters(fileData, {}, [], 'init')
      const list = routers.map(i => {
        let path = i.path
        const splitArr = path.split('/')
        if (splitArr.length === 2 && splitArr[0] === '') {
          path += '/index'
        }
        return {
          abortOnFail: false,
          skipIfExists: true,
          type: 'add',
          path: `src/views${path}.vue`,
          templateFile: `plop-templates/view/${i.template || 'ag'}.hbs`
        }
      })
      const actions = [
        ...list
      ]

      return actions
    }
  })
}

function repla(path = '') {
  const index = path.indexOf(':')
  if (index > -1) {
    return path.slice(0, index - 1)
  }
  return path
}
function handelRouters(data = [], parent = {}, list = [], init) {
  // eslint-disable-next-line no-eval
  const data1 = eval(data)
  data1.map(i => {
    i.name = (parent.name ? parent.name + '/' : '') + i.name
    i.path = (parent.path ? repla(parent.path) + '/' : '') + repla(i.path)
    if (i.children && i.children.length > 0) {
      if (!init) {
        list.push({
          name: i.name,
          path: repla(i.path) + '/index',
          template: 'routerView'
        })
      }
      list.push(...handelRouters(i.children, i))
    } else {
      list.push({
        name: i.name,
        path: repla(i.path),
        template: i.template
      })
    }
  })
  return list
}
